package com.xinchengxd.email.service.impl;

import com.xinchengxd.commons.entity.dto.MailDTO;
import com.xinchengxd.commons.entity.order.OrderItem;
import com.xinchengxd.email.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;

/**
 * @author: 姚新成
 * @Date: 2021/11/16:11:52
 * @Description: 发送邮件
 */

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private TemplateEngine templateEngine;

    @Override
    public void emailSend(MailDTO mailDTO,int status) {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        /*测试数据*/
//        List<Goods> test = new ArrayList<>();
//        test.add(new Goods("核酸检测套餐",new BigDecimal("59.9")));
//        test.add(new Goods("恰饭套餐",new BigDecimal("200")));

//        准备数据
        String isPay = status==1? "您的订单已下单，请尽快支付" : "您的订单超时未支付，已取消";
        String user = mailDTO.getUser();
        String email = mailDTO.getEmail();
        String telephone = mailDTO.getTelephone();
        String address = mailDTO.getAddress();
        String accept = mailDTO.getAccept();
        String orderNo = mailDTO.getOrderNo();
        List<OrderItem> goods = mailDTO.getGoods();
        goods.forEach(s ->{
            s.CreateMoney();
        });

        /*创建上下文*/
        Context context = new Context();
        /*设置属性，在后续会对应填充到模板中的el表达式中*/
        context.setVariable("isPay",isPay);
        context.setVariable("user",user);
        context.setVariable("orderNo",orderNo);
        context.setVariable("accept",accept);
        context.setVariable("telephone",telephone);
        context.setVariable("address",address);
        context.setVariable("goods",goods);
        /*使用指定的index模板，将context内容填充到模板中，最后转换为字符串进行返回*/
        String template = templateEngine.process("index", context);

        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
            helper.setSubject("订单取消通知");
            /*设置发件人，与yml中配置的必须保持一致*/
            helper.setFrom("905796999@qq.com");
            /*设置收件人，可以多个，以,分隔*/
//            helper.setTo(new String[]{"xincheng.y@foxmail.com","1344933373@qq.com"});
            helper.setTo(email);
            /*设置邮件发送日期*/
            helper.setSentDate(new Date());
            /*设置邮件正文,正文样式来自模板*/
            helper.setText(template,true);


            /*发送邮件*/
            javaMailSender.send(mimeMessage);

        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}
